#!/usr/bin/env python
# -*- coding: utf8 -*-

from necrolib import webget
from necrolib import utils
import sys
from necrolib import ConfigObj
from necrolib import datadir
from optparse import OptionParser
import logging

cfg_file = datadir.user_data_dir("necroposter/uploader.cfg")
config = ConfigObj(cfg_file)
logging.basicConfig(level=logging.DEBUG)

class uploader():
	def __init__(self):
		self.check_config()

	def check_config(self):
		try:
		    u = config['fo_user']
		    p = config['fo_pass']
		    if u == '' or p == '':
			logging.info ( "empty cfg")
			u, p = setup_cfg()
		except KeyError:
		    u, p = setup_cfg()
		self.u = u
		self.p = p
		return u, p

	def setup_cfg(self):
		logging.debug( "Starting configuration")
		u = raw_input('Please enter FilEx username-> ')
		p = raw_input('Please enter FilEx password-> ')
		config['fo_user'] = u
		config['fo_pass'] = p
		config.write()
		return u, p

	def upl_file(self, n, c, d):
		print n
		wg = webget()
		wg.c=c
		wg.d=d
		wg.init_cookie(self.u, self.p)
		k = wg.upload_file(n)
		filenum=utils.getnum(utils.get_urls_meta(k[2]))
		print filenum

def opts():
	usage = "usage: %prog [options] file1 file2 file3"
	parser = OptionParser(usage=usage, description="Upload files to FileEx easily", version="0.2")
	parser.add_option("-c", "--category", dest="category", default=1,type="int",
				help="Category of uploaded file", metavar="CATEGORY")
	parser.add_option("-d", "--description", dest="description", default="Automatic upload",
				help="Description of uploaded file", metavar="DESCRIPTION")

	(options, args) = parser.parse_args()
	if not args:
			parser.error( "no files specified")
	return options, args

def main():
	options, args = opts()
	upl=uploader()
	for a in args:
		upl.upl_file(a, c=options.category, d=options.description)


if __name__ == "__main__":
    main()

